package com.linzm.proxy.dynamiccglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author zimingl
 * @Date 2023/8/21 23:53
 * @Description: TODO
 */
public class DynamicCglibProxy {
    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(RealSubject.class);
        enhancer.setCallback(new ProxyInterceptor());
        RealSubject proxySubject = (RealSubject) enhancer.create();
        proxySubject.doSomething();
    }
}
// 原始类
class RealSubject {
    public void doSomething() {
        System.out.println("RealSubject 执行了某些操作。");
    }
}

// MethodInterceptor实现类
class ProxyInterceptor implements MethodInterceptor {
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("代理类执行前的逻辑。");
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("代理类执行后的逻辑。");
        return result;
    }
}
